// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'
import axios from 'axios'
import VueAxios from 'vue-axios'
import live2d from 'live2d4vue'
import Element from "element-ui"

Vue.use(Element)

Vue.prototype.$http = axios;

Vue.config.productionTip = false

Vue.use(live2d)


router.beforeEach((to, from, next) => {
  //验证  
  if (to.matched.some(m => m.meta.requireAuth)) {    // 需要登录 检测用户登录的页面是否需要登录权限
    console.log("页面需要登录")
    console.log(router);
    console.log(window.localStorage);
    if(window.localStorage.token && window.localStorage.isLogin === '1'){ 
      next()
    } else if (to.path != '/login') {
      let token = window.localStorage.token;
      if (token === 'null' || token === '' || token === undefined){
          next({path: '/login'})
          Toast({ message: '检测到您还未登录,请登录后操作！', duration: 1500 })
      }
    } else {  
      next()
    }
  } else {   // 不需要登录
    console.log("该页面需要认证权限")
    console.log(to);
    console.log(window.localStorage);
    next()
  }
})

axios.interceptors.request.use(
  config =>{
    if(store.state.token){
      config.headers.common['token'] =store.state.token
    }
    return config;
  },
  error =>{
    //对请求错误做什么
    return Promise.reject(error);
  })

  //http reponse响应拦截器
axios.interceptors.response.use(
  response =>{
    return response;
  },
  error=>{
    if(error.response){
      switch(error.response.status){
        case 401:
          localStorage.removeItem('token');
          router.replace({
            path: '/views/login',
            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
          })
      }
    }
  })


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store:store,
  components: { App },
  template: '<App/>'
})
